package com.letu.core.utils;

import com.letu.core.exception.code.ExceptionCode;
import com.letu.core.model.FaceRecognitionResult;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Date:2021/12/15
 * Time:11:41
 *
 * @author zjn
 */
@Slf4j
public class FaceIdentifyUtils {

    /**
     * 人脸识别
     *
     * @param exhId
     * @param imgUrl
     * @return
     */
    public static Boolean sendPersonJoinFaceIdentify(String exhId, String imgUrl) {
        if (StringUtils.isBlank(exhId, imgUrl)) {
            throw new NullPointerException();
        }
        Map<String, String> paramsMap = getParamsMapSendPersonJoinCheckVerifyFace(exhId, imgUrl);
        try {
            byte[] bytes = HttpClientUtils.get(new URL(imgUrl));
            // 接口请求response对象
            ByteArrayOutputStream responseByteArrayOutputStream = new ByteArrayOutputStream();
            HttpClientUtils.postFile(new URL("https://ai.exporegist.com/ai/api/Face/FaceDetect"), paramsMap, bytes, responseByteArrayOutputStream);
            Gson gson = new Gson();
            FaceRecognitionResult faceRecognitionResult = gson.fromJson(responseByteArrayOutputStream.toString(), FaceRecognitionResult.class);
            if (!faceRecognitionResult.getStatus().equals(ExceptionCode.OK.getMsg())) {
                return Boolean.FALSE;
            }
        } catch (IOException e) {
            log.error(exhId, "人脸识别出现异常", "imgUrl:" + imgUrl, e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    private static Map<String, String> getParamsMapSendPersonJoinCheckVerifyFace(String exhId, String psjVisitorCard) {
        Map<String, String> paramsMap = new HashMap<>(20);
        paramsMap.put("ExhID", ExhIdUtils.NumberEncode(Integer.parseInt(exhId)));
        paramsMap.put("PsjVisitorCard", psjVisitorCard);
        return paramsMap;
    }

}
